package client;

/**
 * class Insert handles the insert CC in the system
 * 
 * @author Rasmus Stjerne, Joachim Lindholm, Daniel Gramstrup, Pamela Pedersen
 */
public class Insert extends Transaction {
	private double amount; // amount to deposit
	private Input input; // reference to keypad
	private final static int CANCELED = 0; // constant for cancel option

	/**
	 * Insert constructor
	 * 
	 * @param display
	 *            to allow messages to be prompted
	 * @param connection
	 *            to allow connection to server
	 * @param input
	 *            to allow input
	 */
	public Insert(Display display, Connection connection, Input input) {
		super(display, connection);
		this.input = input;
	}

	/**
	 * perform insert transaction
	 */
	@Override
	public void execute() {
		Connection connection = getConnection();
		Display display = getDisplay();
		amount = promptForDepositAmount(); // get total amount to insert
		// check whether user entered an amount or canceled by clicking 0
		if (amount != CANCELED) {
			// inserts the amount on server
			connection.insert(amount);
		} else // user canceled instead of entering amount
		{
			display.displayMessageLine("\nCanceling transaction...");
		}
	}

	/**
	 * prompt user to enter a deposit amount in CC
	 * 
	 * @return user input - 0 is cancel
	 */
	private double promptForDepositAmount() {
		Display display = getDisplay(); // get reference to screen
		display.displayMessage("\nPlease enter amount of KM (Press 0 to cancel): ");
		// Max kilometer limit: 500
		int CC = input.getInt(0, 500);
		// check whether the user canceled or entered a valid amount
		if (CC == CANCELED)
			return CANCELED;
		else {
			return (double) CC;
		}
	}
}